package com.code.monitor.utils;

import com.alibaba.fastjson2.JSON;
import com.code.monitor.model.CacheManager;
import com.code.monitor.model.ServiceInfo;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;

/**
 * @author ggh
 * @date 2023/5/8
 */
public class PushMessageUtil {
    private static final Logger logger = LoggerFactory.getLogger(PushMessageUtil.class);

    /**
     * 推送动态消息到订阅者
     */
    public static void pushMessageToAllSubscriber() {
        List<SocketChannel> subscriberList = CacheManager.getWebSubscriberList();
        if (CollectionUtils.isEmpty(subscriberList)) {
            logger.info("没有websocket订阅者，跳过此步骤");
        }
        subscriberList.forEach((subscriber) -> {
            Collection<ServiceInfo> serviceInfoList = CacheManager.getServiceInfoList();

            String machineInfoJson = JSON.toJSONString(serviceInfoList);
            TextWebSocketFrame machineInfoSocketMessage = new TextWebSocketFrame(machineInfoJson);
            subscriber.writeAndFlush(machineInfoSocketMessage);
        });
    }

    public static void pushMessageToSubscriber(SocketChannel subscriber) {
        if (subscriber == null) {
            logger.info("subscriber为空");
        }
        Collection<ServiceInfo> serviceInfoList = CacheManager.getServiceInfoList();

        String machineInfoJson = JSON.toJSONString(serviceInfoList);
        TextWebSocketFrame machineInfoSocketMessage = new TextWebSocketFrame(machineInfoJson);
        subscriber.writeAndFlush(machineInfoSocketMessage);
    }
}
